package com.example.educationalsystem.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.educationalsystem.common.util.DateFormates;
import com.example.educationalsystem.common.util.ExcelListener;
import com.example.educationalsystem.common.util.ResponseJson;
import com.example.educationalsystem.entity.*;
import com.example.educationalsystem.entity.Teacher;
import com.example.educationalsystem.mapper.ITeacherMapper;
import com.example.educationalsystem.service.ITeacherService;
import com.example.educationalsystem.service.IUserService;
import com.example.educationalsystem.service.IVoteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

import static ch.qos.logback.core.joran.action.ActionConst.NULL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zpc
 * @since 2022-12-02
 */
@Api(value = "/teacher",tags = "教师信息管理")
@RestController
@RequestMapping("/teacher")
public class TeacherController {
    @Autowired
    private ITeacherService iTeacherService;

    @Autowired
    private IUserService iUserService;

    @ApiOperation(value = "导出教师信息",notes = "导出教师信息")
    @ResponseBody
    @GetMapping("Download")
    public void myDownload(HttpServletResponse response, @RequestParam String tableName) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="+ new String(tableName.getBytes(StandardCharsets.UTF_8),"ISO8859-1")+".xls");
        System.out.println(iTeacherService.getBaseMapper().selectList(Wrappers.lambdaQuery()));
        EasyExcel.write(response.getOutputStream(), Teacher.class).sheet(tableName).doWrite(iTeacherService.getBaseMapper().selectList(Wrappers.lambdaQuery()));
    }
    @ApiOperation(value = "导入教师信息",notes = "导入教师信息")
    @ResponseBody
    @PostMapping("Import")
    public ResponseJson myImport(MultipartFile file) {
        ResponseJson responseJson=new ResponseJson();
        try {
            //获取文件名
            String filename = file.getOriginalFilename();
            //获取文件流
            InputStream inputStream = file.getInputStream();
            //实例化实现了AnalysisEventListener接口的类
            ExcelListener listener = new ExcelListener();

            EasyExcelFactory.read(inputStream, Teacher.class, listener).headRowNumber(1).build().readAll();
            //获取数据
            List<Object> list = listener.getDatas();
            if (list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    Teacher Teacher = (Teacher) list.get(i);
                    System.out.println(Teacher.toString());
                    //使用mybatis-plus添加到数据库
                    iTeacherService.save(Teacher);
                    User registerUser=new User();
                    registerUser.setUserEmail("");
                    registerUser.setUserPermissions(2);
                    registerUser.setUserAvatarUrl("");
                    registerUser.setUserId(0);
                    registerUser.setUserPhone("");
                    registerUser.setUserIdentity("教师");
                    String mm = new BCryptPasswordEncoder().encode("123456");
                    registerUser.setUserPassword(mm);
                    registerUser.setUserName(Teacher.getTeacherId());
                    iUserService.save(registerUser);
                }
            }
            responseJson.setStatus(200);
            responseJson.setMsg("导入成功！");
        } catch (Exception e) {
            responseJson.setStatus(400);
            responseJson.setMsg("导入失败！");
            e.printStackTrace();
        }

        return responseJson;
    }
    @GetMapping("/getAllTeacher")
    @ApiOperation(value = "获取所有教师信息",notes = "获取所有教师信息")
    @ApiParam(NULL)
    @ResponseBody
    public ResponseJson getAllTeacher()
    {
        ResponseJson responseJson=new ResponseJson();
        List<Teacher> votelist=iTeacherService.getBaseMapper().selectList(Wrappers.lambdaQuery());
        if(votelist!=null)
        {
            responseJson.setStatus(200);
            responseJson.setMsg("查询成功！");
            responseJson.setData(votelist);

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("查询为空，暂无教师信息！");
        }
        return responseJson;
    }
    @ApiOperation(value = "分页查询教师信息", notes = "分页查询教师信息，需要提供页数和一页大小（即一页几条数据）")
    @GetMapping(value = "/teacherPage")
    @ResponseBody
    public ResponseJson userpage(@RequestParam long current, @RequestParam long size) {
        ResponseJson responseJson = new ResponseJson();
        Page<Teacher> TeacherPage = new Page<>(current, size);
        Page<Teacher> TeacherPages = iTeacherService.getBaseMapper().selectPage(TeacherPage, null);
        responseJson.setMsg("分页查询成功");
        responseJson.setData(TeacherPages);
        responseJson.setStatus(200);
        return responseJson;
    }
    @ApiOperation(value = "增加教师信息",notes = "增加一条教师信息记录")
    @PostMapping("/insertTeacher")
    @ResponseBody
    public ResponseJson insertTeacher(@RequestBody Teacher requestTeacher)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
        String strID = DateFormates.NowDateFormate();
        requestTeacher.setTeacherId(strID);
        Teacher teacherOne=iTeacherService.getBaseMapper().selectOne(queryWrapper.eq("teacher_id",requestTeacher.getTeacherId()));
        if(teacherOne==null)
        {
            Boolean result=iTeacherService.save(requestTeacher);
            User registerUser=new User();
            registerUser.setUserEmail("");
            registerUser.setUserPermissions(2);
            registerUser.setUserAvatarUrl("");
            registerUser.setUserId(0);
            registerUser.setUserPhone("");
            registerUser.setUserIdentity("教师");
            String mm = new BCryptPasswordEncoder().encode("123456");
            registerUser.setUserPassword(mm);
            registerUser.setUserName(requestTeacher.getTeacherId());
            iUserService.save(registerUser);
            if(result)
            {
                responseJson.setMsg("增加成功！");
                responseJson.setStatus(200);
                responseJson.setData(requestTeacher);

            }
            else
            {
                responseJson.setStatus(400);
                responseJson.setMsg("增加失败！");
            }
        }
        else
        {
            responseJson.setStatus(400);
            responseJson.setMsg("该教师信息记录已存在！");
        }
        return responseJson;
    }

    @ApiOperation(value = "批量删除教师信息",notes = "根据教师编号，删除多条教师信息")
    @DeleteMapping("/deleteTeachers")
    @ResponseBody
    public  ResponseJson deleteTeachers( @ApiParam(name = "Ids", value = "教师IDs", required = true) @RequestParam String Ids)
    {
        ResponseJson responseJson=new ResponseJson();
        String[] idArr = Ids.split(",");
        List<String> idList = Arrays.asList(idArr);
        for(int i=0;i<idList.size();i++)
        {
            QueryWrapper<User> userQueryWrapper=new QueryWrapper<>();
            iUserService.getBaseMapper().delete(userQueryWrapper.eq("user_name",iTeacherService.getById(idList.get(i)).getTeacherId()));
        }
        boolean result=iTeacherService.removeByIds(idList);
        System.out.println(result);
        if(result)
        {
//            responseJson.setData(courseOne);
            responseJson.setMsg("批量删除成功！");
            responseJson.setStatus(200);
        }
        else
        {
            responseJson.setMsg("批量删除失败");
            responseJson.setStatus(400);
        }
        return responseJson;

    }
    @ApiOperation(value = "删除教师信息",notes = "根据教师ID，删除一条教师信息")
    @DeleteMapping("/deleteTeacher")
    @ResponseBody
    public  ResponseJson deleteTeacher( @ApiParam(name = "teacherId", value = "教师编号", required = true) @RequestParam String teacherId)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
        Teacher teacherOne=iTeacherService.getBaseMapper().selectOne(queryWrapper.eq("teacher_id",teacherId));
        if(teacherOne!=null)
        {
            int result=iTeacherService.getBaseMapper().deleteById(teacherOne.getTeacherId());
            System.out.println(result);
            if(result==1)
            {
                responseJson.setData(teacherOne);
                responseJson.setMsg("删除成功！");
                responseJson.setStatus(200);
            }
            else
            {
                responseJson.setMsg("删除失败");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setStatus(404);
            responseJson.setMsg("该教师信息不存在！");
        }
        return responseJson;

    }

    @ApiOperation(value = "更新教师信息",notes = "更新教师信息，必须填写教师ID")
    @PutMapping("/updateTeacher")
    @ResponseBody
    public ResponseJson updateTeacher(@RequestBody  Teacher resquestTeacher)
    {
        ResponseJson responseJson=new ResponseJson();
        QueryWrapper<Teacher> queryWrapper=new QueryWrapper<>();
        Teacher teacherOne=iTeacherService.getBaseMapper().selectOne(queryWrapper.eq("teacher_id",resquestTeacher.getTeacherId()));
        if(teacherOne!=null)
        {
            int result=iTeacherService.getBaseMapper().update(resquestTeacher,queryWrapper.eq("teacher_id",resquestTeacher.getTeacherId()));
            if(result==1)
            {
                responseJson.setMsg("更新成功！");
                responseJson.setStatus(200);
                responseJson.setData(resquestTeacher);
            }
            else {
                responseJson.setMsg("更新失败！");
                responseJson.setStatus(400);
            }

        }
        else
        {
            responseJson.setMsg("该教师信息不存在");
            responseJson.setStatus(404);
        }
        return responseJson;
    }
}

